package TCP.DoubleWay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * 定义两个线程
 * 一个负责接收消息
 * 一个负责发送消息
 */
class clientSend extends Thread
{
    private Socket socket;
    
    public clientSend (Socket socket)
    {
        this.socket = socket;
    }
    
    private void sendMessage ()
    {
        try(Scanner scan = new Scanner(System.in);
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream()))
        {
            while(true)
            {
                String str = scan.next();
                
                printWriter.println(str);
                printWriter.flush();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run ()
    {
        this.sendMessage();
    }
}

class clientReceive extends Thread
{
    private Socket socket;
    
    public clientReceive (Socket socket)
    {
        this.socket = socket;
    }
    
    private void getMessage()
    {
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())))
        {
            while(true)
            {
                String str = bufferedReader.readLine();
    
                System.out.println("服务端说：" + str);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run ()
    {
        this.getMessage();
    }
}
public class OneSocket
{
    public static void main (String[] args)
    {
        try
        {
            Socket socket = new Socket("127.0.0.1", 8888);
            
            System.out.println("连接成功");
            
            new clientSend(socket).start();
            new clientReceive(socket).start();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
